/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package team;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Vector;
import javax.ejb.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

/**
 *
 * @author denaas
 */
public class TeamBean {

    private Team team = new Team();
    private DataSource dataSource;

    /**
     * @return the dataSource
     */
    /**
     * @return the team
     */
    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }

    /**
     * @param team the team to set
     */
    protected DataSource getDataSource() {
        return dataSource;
    }

    protected void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //</editor-fold>
    private EntityContext context;

    protected EntityContext getContext() {
        return context;
    }

    // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click the + sign on the left to edit the code.">
    // TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise beans, Web services)
    // TODO Add business methods
    // TODO Add create methods
    /**
     * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
     */
    public void setEntityContext(EntityContext aContext) {
        try {
            context = aContext;
            InitialContext ic = new InitialContext();
            Object objRef = ic.lookup("jdbc/den");
            setDataSource((DataSource) PortableRemoteObject.narrow(objRef, DataSource.class));
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @see javax.ejb.EntityBean#ejbActivate()
     */
    public void ejbActivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbPassivate()
     */
    public void ejbPassivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbRemove()
     */
    public void ejbRemove() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("DELETE FROM teams WHERE id = ?");
            stmt.setInt(1, getTeam().getId().intValue());

            if (stmt.executeUpdate() < 1) {
                throw new NoSuchEntityException();
            }

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    /**
     * @see javax.ejb.EntityBean#unsetEntityContext()
     */
    public void unsetEntityContext() {
        context = null;
    }

    /**
     * @see javax.ejb.EntityBean#ejbLoad()
     */
    public void ejbLoad() {
        Object key = getContext().getPrimaryKey();
        if (key instanceof String) {
            getTeam().setId(new Integer((String) key));
        } else if (key instanceof Integer) {
            getTeam().setId((Integer) key);
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("Select * from teams where id = ?");
            stmt.setInt(1, getTeam().getId().intValue());
            res = stmt.executeQuery();
            if (!res.next()) {
                throw new NoSuchEntityException();
            }
            getTeam().setCity(res.getString("city"));
            getTeam().setName(res.getString("name"));
            getTeam().setSportId(new Integer(res.getInt("sportid")));


        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    /**
     * @see javax.ejb.EntityBean#ejbStore()
     */
    public void ejbStore() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("update teams set sportid=?, name=?, city=? where id = ?");
            stmt.setInt(1, getTeam().getSportId().intValue());
            stmt.setString(2, getTeam().getName());
            stmt.setString(3, getTeam().getCity());
            stmt.setInt(4, getTeam().getId().intValue());

            if (stmt.executeUpdate() < 1) {
                throw new NoSuchEntityException();
            }


        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    // </editor-fold>
    /**
     * See EJB 2.0 and EJB 2.1 section 12.2.5
     */
    public Integer ejbCreate(Team tm) throws CreateException {
        setTeam(tm);

        Connection conn = null;
        PreparedStatement stmt = null;
        PreparedStatement stmt2 = null;
        ResultSet res2 = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("INSERT INTO teams (id,city,name,sportid)"
                    + "VALUES (SEQTEAM.NEXTVAL, ?,?,?)");
            stmt.setString(1, getTeam().getCity());
            stmt.setString(2, getTeam().getName());
            stmt.setInt(3, getTeam().getSportId().intValue());

            if (stmt.executeUpdate() != 1) {
                throw new CreateException();
            }

            stmt2 = conn.prepareStatement("select seqteam.currval from teams");
            res2 = stmt2.executeQuery();
            res2.next();
            getTeam().setId(new Integer(res2.getInt(1)));


            return getTeam().getId();

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                stmt2.close();
                res2.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public void ejbPostCreate(Team tm) throws CreateException {
    }

    public java.lang.Integer ejbFindByPrimaryKey(java.lang.Integer aKey) throws ObjectNotFoundException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from teams where id=?");
            stmt.setInt(1, aKey.intValue());
            res = stmt.executeQuery();

            if (!res.next()) {
                throw new ObjectNotFoundException();
            }


            return aKey;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public Collection ejbFindByName(String aName) throws FinderException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from teams where name=?");
            stmt.setString(1, aName);
            res = stmt.executeQuery();

            Vector keys = new Vector();

            while (res.next()) {
                String empno = res.getString(1);
                keys.addElement(empno);
            }


            return keys;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public Collection ejbFindAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from teams");
            res = stmt.executeQuery();

            Vector keys = new Vector();

            while (res.next()) {
                String empno = res.getString(1);
                keys.addElement(empno);
            }


            return keys;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }
}
